package java核心及工具类.Format类;

import java.awt.Color;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Currency;
import java.util.Date;
import java.util.Locale;

public class fpTest {

	public static void main(String[] args) throws ParseException{
		System.out.println(convertDollar2Cent("12030.0"));//将元转换成分
		System.out.println(Arrays.toString(getLocalePatternInfo()));
		System.out.println(checkLength(1234.45, 4, 2));
	}
	public static String convertDollar2Cent(String str) {
		//DecimalFormat.DecimalFormat(String pattern)
	    DecimalFormat df = new DecimalFormat("0.00");
	    //StringBuffer DecimalFormat.format(double number, StringBuffer result, FieldPosition fieldPosition)
	    StringBuffer sb = df.format(Double.parseDouble(str),new StringBuffer(), new FieldPosition(DateFormat.DATE_FIELD));
	    System.out.println(sb.toString());
	    System.out.println((new FieldPosition(NumberFormat.FRACTION_FIELD)));
	    int idx = sb.toString().indexOf(".");//找到"."在sb中的索引位置：idx
	    sb.deleteCharAt(idx);//删除索引位置处的字符"."
	    System.out.println(sb.charAt(2));
//	    for (; sb.length() != 1;) {
//	        if(sb.charAt(0) == '0') {
//	            sb.deleteCharAt(0);
//	            System.out.println(sb.toString());
//	        } else {
//	            break;
//	        }
//	    }
	    return sb.toString();
	}
	public static String[] getLocalePatternInfo() throws ParseException {
		Date date = new Date();
		System.out.println(date);//Sat Jul 09 09:45:28 CST 2022
		String info[] = new String[6];
		DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT,Locale.US);//Locale.getDefault());
		FieldPosition yearPosition = new FieldPosition(DateFormat.YEAR_FIELD);
		StringBuffer buffer = new StringBuffer();
		StringBuffer format = dateFormat.format(date, buffer, yearPosition);
		String pattern = new SimpleDateFormat().toPattern();
		String datePattern = pattern.substring(0, format.length());
		
		String hourPattern = pattern.substring(format.length() + 1);

		// infos sur le format des dates
		int yearIdx = yearPosition.getBeginIndex() - 1;
		info[0] = format.substring(yearIdx, yearIdx + 1);
		info[1] = "\\" + info[0];
		info[2] = datePattern;

		//infos sur le format des heures
		info[3] = hourPattern.substring(2, 3);
		info[4] = "\\" + info[3];
		info[5] = hourPattern + info[3] + "ss";
		return info;
	}
	
	 //此方法将确保输入数值不超过指定的限制。
	 
	static boolean checkLength(Number input, Integer intSize, Integer fracSize) {
	//private boolean checkLength(Number input, Integer intSize, Integer fracSize) {
		//input:输入要检查其长度的数字。
		//intSize:在十进制之前允许的位数的上限。
		//fracSize:小数制后允许的位数的上限。
		//checkLength(1234.56, 4, 2)-->true
		//checkLength(12345.56, 4, 2)-->false  因为整数12345的位数大于4
		//checkLength(1234.567, 4, 2)-->false  因为小数567的位数大于2
	    if (input != null && (intSize != null || fracSize != null)) {
	        double value = Math.abs(input.doubleValue());//输入数的绝对值
	        System.out.println(value);
	        if (intSize != null) {//整数位数
	            double intLimit = Math.pow(10, intSize.intValue());//10的整数位数次方
	            if ((long) value >= (long) intLimit)
	                return false;
	        }

	        if (fracSize != null) {
	            // @todo: should find a much more efficient way of finding the no. of fractional digits
	            StringBuffer buf = new StringBuffer();
	            //FieldPosition fp = new FieldPosition(NumberFormat.FRACTION_FIELD);//设置能获取分数部分的起始及终止索引
	            FieldPosition fp = new FieldPosition(1);//同上，设置能获取分数部分的起始及终止索引
	            //FieldPosition fp = new FieldPosition(0);//设置能获取整数部分的起始及终止索引
	            //java.text.NumberFormat：
	            //public static final int FRACTION_FIELD 1
	            //public static final int INTEGER_FIELD  0
	            
	            NumberFormat df = NumberFormat.getNumberInstance();
	            df.setGroupingUsed(false);//不以此格式使用分组
	            df.setMaximumFractionDigits(20); // THIS SHOULD BE SUFFICIENT 设置数字的分数部分中允许的最大位数。
	            
	            //public StringBuffer format(Object number,StringBuffer toAppendTo,FieldPosition pos)
	            df.format(value, buf, fp);
	            System.out.println(buf.toString());//1234.45
	            String fracString = buf.substring(fp.getBeginIndex(), fp.getEndIndex());
	            System.out.println(fracString);//45
	            
	            if (fracString != null && fracString.length() > fracSize.intValue())
	                return false;
	        }
	    }
	    return true;
	}
	
	@Override
	public final StringBuffer format(Object obj,StringBuffer toAppendTo,FieldPosition fieldPosition){
		if (obj instanceof Color){
			return format((Color)obj, toAppendTo, fieldPosition);
		}
		else if (obj instanceof Number){
			return format(new Color(((Number)obj).intValue()),toAppendTo, fieldPosition);
		}
		else {
			throw new IllegalArgumentException(_LOG.getMessage("CANNOT_FORMAT_GIVEN_OBJECT_AS_COLOR"));
		}
	}
}
